import HttpRequestInterface from "../HttpRequestInterface";

export default class WxRequest extends HttpRequestInterface {
  request(url, method = 'POST', data = null, options = null) {
    options = options || {};
    let {onSuccess, onFail, header} = options;
    if (!header) {
      header = {
        'CONTENT_TYPE': 'application/json',
        'Accept': 'application/json',
      };
    }
    wx.request({
      url: url,
      data: data,
      method: method,
      header: header,
      success: res => {
        console.log("WxRequest success", url, res.data);
        if (res.statusCode === 200) {
          onSuccess && onSuccess(res.data);
        } else {
          onFail && onFail('request error');
        }
      },
      // @ts-ignore
      fail: (res) => {
        console.log("WxRequest fail", url, res);
        onFail && onFail('request error');
      }
    });
  }

  post(url, data, options = null) {
    this.request(url, "POST", data, options);
  }

  postJson(url, data = {}, options = null) {
    this.post(url, data, options);
  }

  getJson(url, data = {}, options = null) {
    options = options || {};
    let {onSuccess, onFail} = options;
    let newOptions = Object.assign({}, options, {
      onSuccess: (responseText) => {
        try {
          onSuccess && onSuccess(JSON.parse(responseText));
        } catch (e) {
          onFail && onFail(e.toString());
        }
      }
    });
    this.request(url, "GET", data, newOptions);
  }
}
